cmake_minimum_required(VERSION 2.8)
project(asn1c C)

set(CMAKE_C_STANDARD 11)

set(SYSTEM_CPU_COMPILER "${CMAKE_SYSTEM_NAME}_${CMAKE_SYSTEM_PROCESSOR}_${CMAKE_C_COMPILER_ID}")
string(TOLOWER "${SYSTEM_CPU_COMPILER}" SYSTEM_CPU_COMPILER)
message("SYSTEM_CPU_COMPILER: ${SYSTEM_CPU_COMPILER}")

set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${PROJECT_SOURCE_DIR}/bin)
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${PROJECT_SOURCE_DIR}/bin)

add_definitions(-DASN_DISABLE_OER_SUPPORT=1)

# cd ${DST_DIR} && mv `ls | grep -v '^NGAP_'` ${PROJECT_SOURCE_DIR}/skeletons && cd ..

macro(compile_asn1 prefix srcDir dstDir options ResultFlag)
   # Warning: if you modify ASN.1 source file to generate new C files, cmake should be re-run instead of make
   execute_process(COMMAND ${PROJECT_SOURCE_DIR}/tools/asn1c_compile.sh ${prefix} ${srcDir} ${dstDir} ${options} RESULT_VARIABLE ret)
   if (NOT ${ret} STREQUAL 0)
      message(FATAL_ERROR "${ret}: error")
   endif (NOT ${ret} STREQUAL 0)
   execute_process(COMMAND ${PROJECT_SOURCE_DIR}/tools/asn1c_skeletons.sh ${prefix} ${dstDir} "${PROJECT_SOURCE_DIR}/skeletons" RESULT_VARIABLE ret)

   add_custom_target (
     ${ResultFlag} ALL
     COMMAND ${PROJECT_SOURCE_DIR}/tools/asn1c_compile.sh ${prefix} ${srcDir} ${dstDir} ${options}
	 COMMAND ${PROJECT_SOURCE_DIR}/tools/asn1c_skeletons.sh ${prefix} ${dstDir} "${PROJECT_SOURCE_DIR}/skeletons"
     DEPENDS ${srcDir}
   )
endmacro(compile_asn1)

# NGAP
set(NGAP_PREFIX "NGAP_")
set(NGAP_DST_DIR ${PROJECT_SOURCE_DIR}/ngap)
set(NGAP_ASN_FILE ${PROJECT_SOURCE_DIR}/asn1Files/38413-g10.asn1)
compile_asn1("${NGAP_PREFIX}" "${NGAP_ASN_FILE}" "${NGAP_DST_DIR}" "-findirect-choice -fno-include-deps" ngap_flag)
file(GLOB_RECURSE NGAP_LIB_SRCS "${PROJECT_SOURCE_DIR}/ngap/*.c")
add_library(ngap_asn1_${SYSTEM_CPU_COMPILER} ${NGAP_LIB_SRCS})
add_dependencies(ngap_asn1_${SYSTEM_CPU_COMPILER} ngap_flag)
include_directories(${PROJECT_SOURCE_DIR}/skeletons)
include_directories(${PROJECT_SOURCE_DIR}/ngap)

# NR RRC
set(NR_RRC_PREFIX "NR_RRC_")
set(NR_RRC_DST_DIR ${PROJECT_SOURCE_DIR}/nr_rrc)
set(NR_RRC_ASN_FILE ${PROJECT_SOURCE_DIR}/asn1Files/nr-rrc-15.6.0.asn1)
compile_asn1("${NR_RRC_PREFIX}" "${NR_RRC_ASN_FILE}" "${NR_RRC_DST_DIR}" "-findirect-choice" nr_rrc_flag)
file(GLOB_RECURSE NR_RRC_LIB_SRCS "${PROJECT_SOURCE_DIR}/nr_rrc/*.c")
add_library(nr_rrc_asn1_${SYSTEM_CPU_COMPILER} ${NR_RRC_LIB_SRCS})
add_dependencies(nr_rrc_asn1_${SYSTEM_CPU_COMPILER} nr_rrc_flag)
include_directories(${PROJECT_SOURCE_DIR}/skeletons)
include_directories(${PROJECT_SOURCE_DIR}/nr_rrc)

file(GLOB_RECURSE ASN1C_LIB_SRCS "${PROJECT_SOURCE_DIR}/skeletons/*.c")
add_library(asn1c_${SYSTEM_CPU_COMPILER} ${ASN1C_LIB_SRCS})
add_dependencies(asn1c_${SYSTEM_CPU_COMPILER} ngap_flag nr_rrc_flag)


#add_executable(asn1clib main.c)